package com.github.linmt.dbdoc4j.metadata.query.base;

import com.github.linmt.dbdoc4j.metadata.exception.QueryMetaDataException;
import com.github.linmt.dbdoc4j.metadata.model.standard.TableModel;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * User: Linmt
 * Date: 2022/12/2
 * Time: 19:36
 * Description: No Description
 */
public abstract class AbstractMetaDataQueryTemplate implements MetaDataQueryOperations {
    private DataSource dataSource;
    private Connection connection;

    public AbstractMetaDataQueryTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public List<TableModel> queryTableMetaData() throws QueryMetaDataException {
        return queryTableMetaData(null);
    }

    @Override
    public List<TableModel> queryTableMetaData(String[] includeTablePatterns) throws QueryMetaDataException {
        return queryTableMetaData(includeTablePatterns, null);
    }


    @Override
    public DataSource getDataSource() {
        return this.dataSource;
    }

    @Override
    public String getSchema() throws QueryMetaDataException {
        try {
            return getConnection().getSchema();
        } catch (SQLException e) {
            throw new QueryMetaDataException("获取数据库连接失败," + e.getMessage());
        }
    }

    @Override
    public String getCatalog() throws QueryMetaDataException {
        try {
            return getConnection().getCatalog();
        } catch (SQLException e) {
            throw new QueryMetaDataException("获取数据库连接失败," + e.getMessage());
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     * @throws QueryMetaDataException
     */
    protected Connection getConnection() throws QueryMetaDataException {
        try {
            if (connection != null && !connection.isClosed()) {
                return this.connection;
            }
        } catch (SQLException e) {
        }

        try {
            this.connection = this.getDataSource().getConnection();
            return this.connection;
        } catch (SQLException e) {
            throw new QueryMetaDataException("获取数据库连接失败," + e.getMessage());
        }
    }

    /**
     * 关闭连接
     */
    protected void closeConnect() {
        if (this.connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

